  

<?php

class DBConnection {
  
    var $database = "db_smartlocks";
    var $connection;

    public function connect() {  
        $filename= __DIR__."/../../config/properties.ini"; 
        $prop = parse_ini_file($filename);
        
        $user = $prop['user'];
        $pwd = $prop['pwd'];
        $host = $prop['host'];   

        $this->connection = mysqli_connect($host, $user, $pwd , $this->database);
        $error = mysqli_connect_errno();
        if ($error > 0) {
            printf("Echec de la connexion : %s\n", $this->connection->connect_error);
            printf("Connection %s on host %s \n", $user,$host);
            var_dump($this->connection);
            var_dump($error);
            exit();
        }
        return $this->connection;
    }

    public function getConnection() {
        return $this->connection;
    }

    public function querySingle($sql) {
        $r = $this->query_($sql);
        return $r->fetch_assoc();
    }

    public function query($sql) {
        $r = $this->query_($sql);
        if ($r) {
            return $r;
        } else {
            echo 'Error during processing request: ' . $sql . '</br>';
            echo '<br>' . $sql . '</br>';
            var_dump($r);
            return false;
        }
    }

    public function queryAll($sql) {
        $r = $this->query_($sql);
        if (mysqli_num_rows($r) == 0) {
            return [];
        } else {
            $results_array = array();
            while ($row = $r->fetch_assoc()) {
                $results_array[] = $row;
            }
            return $results_array;
        }
    }

    private function query_($sql) {
        $r = $this->connection->query($sql);
        return $r;
    }

    public function close() {
        mysqli_close($this->connection);
    }

}
?>